#!/usr/bin/env python

import sys, re, urllib

server_name = 'www.pythonchallenge.com'
file_name = '/pc/def/linkedlist.php?nothing='
number = 12345
local_name = 'test.txt'
time = 0
while time < 1000:
    remote_addr = 'http://%s%s%d' %(server_name, file_name, number)
    print 'Open', remote_addr
    urllib.urlretrieve(remote_addr, local_name)
    text = ''.join(line.rstrip() for line in open(local_name).readlines())
    print 'Content:', text
    mo = re.search('and the next nothing is (\d+)', text)
    if mo == None:
        if re.search('Divide by two and keep going', text) != None:
            number /= 2
            time += 1
            continue
        break
    number = int(mo.group(1))
    time += 1
